package org.ldh.web.servlet;

import org.ldh.domain.User;
import org.ldh.service.UserService;
import org.ldh.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        //获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");
        //调用service层
        UserService userService = new UserServiceImpl();
        //根据username和password查询数据库
        User user = userService.findByNameAndPass(username,password);
        //判断用户名和密码是否正确
        if(user == null){
            //用户名或密码错误，给予提示信息，跳转登录页面
            request.setAttribute("error","您输入的用户名或密码错误");
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }else{
            //用户名和密码正确
            if(remember != null && remember.equals("remember-password")){
                //用户要保存密码
                Cookie cookie = new Cookie("remember",remember);
                cookie.setMaxAge(86400); //保存密码一天 24*60*60
                response.addCookie(cookie);
            }
            //保存用户信息到session中，跳转到主页面
            request.getSession().setAttribute("session_user",user);
            request.getRequestDispatcher("/WEB-INF/pages/main.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
